package com.bryantkobe.myspringcode.advice;

import com.bryantkobe.myspringcode.exception.ErrorResult;
import com.bryantkobe.myspringcode.exception.SuccessResult;
import com.bryantkobe.myspringcode.inter.IgnoreResponseWrap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @description: 响应体统一封装
 * @author: alienwarezzl
 * @date: 2025/9/23
 */
@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
    private static final Logger log = LoggerFactory.getLogger(GlobalResponseAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        return !returnType.hasMethodAnnotation(IgnoreResponseWrap.class) &&
                !returnType.getParameterType().equals(ErrorResult.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {


        if (body instanceof SuccessResult) {
            return body;
        }

        // 使用JDK21字符串模板增强日志可读性
        String path = request.getURI().getPath();
        log.info(String.format("API响应封装: {"+path+"} - 成功"));

        if (body instanceof ErrorResult) {
            return body;
        }

        return body;
    }
}
